package dao;

import beans.ManagerInfoBean;
import utils.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Objects;

public class ManagerInfoDaoImpl implements ManagerInfoDao {
    @Override
    public int insertManager(ManagerInfoBean maj) {
        int result = 0;
        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = JDBCUtil.getConnection();

            String sql = "INSERT INTO ManagerInfo VALUES (?,?,?)";
            ps = Objects.requireNonNull(conn).prepareStatement(sql);
            ps.setObject(1, maj.getId());
            ps.setObject(2, maj.getPassword());
            ps.setObject(3, maj.getIsRoot());

            result = ps.executeUpdate();

        } catch (Exception e) {
            return result;
        } finally {
            JDBCUtil.closeAll(null, ps, conn);
        }
        return result;
    }

    @Override
    public String getPasswordById(String id) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String pwd = "";

        try {
            conn = JDBCUtil.getConnection();
            String sql = "SELECT password FROM ManagerInfo WHERE id=?";
            ps = Objects.requireNonNull(conn).prepareStatement(sql);
            ps.setObject(1, id);
            rs = ps.executeQuery();

            while (rs.next()) {
                pwd = rs.getString("password");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.closeAll(rs, ps, conn);
        }
        return pwd;
    }

    @Override
    public String getIsRootById(String id) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String isRoot = "";

        try {
            conn = JDBCUtil.getConnection();
            String sql = "SELECT isRoot FROM ManagerInfo WHERE id=?";
            ps = Objects.requireNonNull(conn).prepareStatement(sql);
            ps.setObject(1, id);
            rs = ps.executeQuery();

            while (rs.next()) {
                isRoot = rs.getString("isRoot");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.closeAll(rs, ps, conn);
        }
        return isRoot;
    }

}
